$(function () {
    //  按钮生成器
    generateButton($('#north'));
    let columns = [[
        {field: 'id', title: '编号', align: 'center', halign: 'center', sortable: true, hidden: true},
        {
            field: 'loginName',
            width: 100,
            title: '登录名',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {required: true}
            }
        },
        {
            field: 'loginPassword',
            width: 100,
            title: '密码',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'passwordbox', options: {required: true}
            },
            formatter: (v, r, i) => {
                return '******';
            }
        },
        {
            field: 'userName',
            width: 100,
            title: '姓名',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'userSex',
            width: 100,
            title: '性别',
            align: 'center',
            halign: 'center',
            sortable: true,
            formatter: (v, r, i) => {
                if (v == 1) return '男';
                if (v == 0) return '女';
                return '';
            },
            editor: {
                type: 'combobox', options: {
                    data: [{id: 1, text: '男'}, {id: 0, text: '女'}],
                    value: 1,
                    panelHeight: 'auto',
                    textField: 'text',
                    valueField: 'id',
                    editable: false,
                }
            }
        },
        {
            field: 'remarks', width: 100, title: '备注', align: 'center', halign: 'center', sortable: true, editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'userAddress',
            width: 100,
            title: '住址',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {}
            }
        },
        {
            field: 'userPhone',
            width: 100,
            title: '电话',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'textbox', options: {validType: 'phone'}
            }
        },
        {
            field: 'projectId',
            width: 100,
            title: '工程名绑定',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'combobox', options: {
                    url: 'jcProject/listQuery',
                    textField: 'projectName',
                    valueField: 'id',
                    limitToList: true,
                    required: false
                }
            }
        },
        {
            field: 'userState',
            width: 100,
            title: '状态',
            align: 'center',
            halign: 'center',
            sortable: true,
            editor: {
                type: 'combobox', options: {
                    data: [{id: 1, text: '正常'}, {id: 0, text: '停用'}],
                    value: 1,
                    panelHeight: 'auto',
                    textField: 'text',
                    valueField: 'id',
                    editable: false,
                    required: true
                }
            },
            formatter: (v, r, i) => {
                return v == 1 ? '正常' : '停用';
            }
        },
    ]];
    setDatagridColumnOpts($('body').data('menu_id'), $('#e_grid'), columns, edatagrid);
    edatagridDtl();
    bindEnterEvents()
})

function edatagrid(columns) {
    $('#e_grid').edatagrid({
        method: 'GET',
        param: {},
        url: 'sysUser/listQuery',
        saveUrl: 'sysUser/insertSelective',
        updateUrl: 'sysUser/updateSelective',
        destroyUrl: 'sysUser/deleteByPk',
        idField: 'id',
        destroyMsg: {
            norecord: {	// when no record is selected
                title: '警告',
                msg: '未选中任何数据'
            },
            confirm: {	// when select a row
                title: '确认',
                msg: '确定删除吗?删除后不可恢复!'
            }
        },
        loadFilter: pageFilter,
        pagination: true,
        // pagePosition: 'top',
        pageSize: 200,
        pageNumber: 1,
        pageList: [200, 400, 600, 800, 1000],
        striped: true,
        fit: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        showFooter: true,
        singleSelect: true,
        columns: columns,
        onLoadSuccess: function () {
            $(this).datagrid('enableFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onLoadError: function () {
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onBeforeLoad: function (param) {
            $(this).datagrid('destroyFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('disable');
                }
            })
            return true;
        },
        onSuccess: function (index, row) {
            $(this).edatagrid('reload');
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
            } else {
                $(this).edatagrid('enableEditing');
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onDestroy: function (index, row) {
            $(this).edatagrid('reload');
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
            } else {
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onError: function (index, row) {
            $.messager.show({title: '提示', msg: row.message});
        },
        onClickRow: function (index, row) {
            //  更改明细的URL
            $('#e_grid_dtl').edatagrid({
                url: 'sysUserRoleGroup/listQuery',
                queryParams: {sysUserId: row.id}
            })

            // 更新用户和客户的关联关系
            $('#e_grid_contact').edatagrid({
                url: 'usercontact/listQuery',
                queryParams: {user_id: row.id}
            })
        },
        onResizeColumn: function (f, w) {
            columnResizeEvent($('body').data('menu_id'), f, w);
        },
    })
}

function edatagridDtl() {
    $('#e_grid_dtl').edatagrid({
        method: 'GET',
        param: {},
        title: '对应角色组',
        url: '',
        saveUrl: 'sysUserRoleGroup/insertSelective',
        updateUrl: 'sysUserRoleGroup/updateSelective',
        destroyUrl: 'sysUserRoleGroup/deleteByPk',
        idField: 'id',
        destroyMsg: {
            norecord: {	// when no record is selected
                title: '警告',
                msg: '未选中任何数据'
            },
            confirm: {	// when select a row
                title: '确认',
                msg: '确定删除吗?删除后不可恢复!'
            }
        },
        loadFilter: pageFilter,
        pagination: true,
        pageSize: 200,
        pageNumber: 1,
        pageList: [200, 400, 600, 800, 1000],
        striped: true,
        fit: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        showFooter: true,
        singleSelect: true,
        columns: [[
            {field: 'id', title: '编号', align: 'center', halign: 'center', sortable: true, hidden: true},
            {
                field: 'sysRoleGroupId',
                width: 100,
                title: '角色组',
                align: 'center',
                halign: 'center',
                sortable: true,
                editor: {
                    type: 'combobox', options: {
                        url: 'sysRoleGroup/listQuery',
                        method: 'GET',
                        textField: 'groupName',
                        valueField: 'id',
                        limitToList: true,
                        panelHeight: 200,
                        required: true
                    }
                },
                formatter: (v, r, i) => {
                    if (!v) return '';
                    let prefix = 'jc_user_role_group';
                    if (sessionStorage.getItem(prefix + `_` + v) == undefined) {
                        let name = JSON.parse($.ajax({
                            url: `sysRoleGroup/queryByPk/${v}`,
                            async: false,
                            dataType: 'json',
                            type: 'GET'
                        }).responseText)['groupName'];
                        sessionStorage.setItem(prefix + `_` + v, name);
                    }
                    return sessionStorage.getItem(prefix + `_` + v);
                }
            },
            {
                field: 'sysUserId',
                width: 100,
                hidden: true,
                title: '用户名',
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {}},
                formatter: (v, r, i) => {
                    if (!v) return '';
                    let prefix = 'jc_user_user';
                    if (sessionStorage.getItem(prefix + `_` + v) == undefined) {
                        let name = JSON.parse($.ajax({
                            url: `sysUser/queryByPk/${v}`,
                            async: false,
                            dataType: 'json',
                            type: 'GET'
                        }).responseText)['userName'];
                        sessionStorage.setItem(prefix + `_` + v, name);
                    }
                    return sessionStorage.getItem(prefix + `_` + v);
                },
                sortable: true,
            },
        ]],
        onAdd: function (index, row) {
            let editor = $(this).edatagrid('getEditor', {
                index: index,
                field: 'sysUserId'
            })
            let selected = $('#e_grid').edatagrid('getSelected');
            if (selected != undefined) {
                $(editor.target).textbox('setValue', selected.id);
            }
        },
        onEdit: function (index, row) {
            let editor = $(this).edatagrid('getEditor', {
                index: index,
                field: 'sysUserId'
            })
            let selected = $('#e_grid').edatagrid('getSelected');
            if (selected != undefined) {
                $(editor.target).combobox('setValue', selected.id);
            }
        },
        onBeforeSave: function (index) {
            let editor = $(this).edatagrid('getEditor', {
                index: index,
                field: 'sysUserId'
            });
            return !!$(editor.target).textbox('getValue');
        },
        onLoadSuccess: function () {
            $(this).datagrid('enableFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onLoadError: function () {
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('enable');
                }
            })
        },
        onBeforeLoad: function (param) {
            $(this).datagrid('destroyFilter');
            $('.easyui-linkbutton').each(function () {
                if ($(this).linkbutton('options').text == '查询') {
                    $(this).linkbutton('disable');
                }
            })
            return true;
        },
        onSuccess: function (index, row) {
            $(this).edatagrid('reload');
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
                sessionStorage.clear();
            } else {
                $(this).edatagrid('enableEditing');
                $.messager.alert('提示', row.message, 'warning')
            }
        },
        onDestroy: function (index, row) {
            if (row.success) {
                $.messager.show({title: '提示', msg: row.message});
                sessionStorage.clear();
            } else {
                $.messager.alert('提示', row.message, 'warning')
            }
            $(this).edatagrid('reload');
        },
        onError: function (index, row) {
            $.messager.show({title: '提示', msg: row.message});
        },
        toolbar: [
            {
                iconCls: 'icon-reload', text: '刷新', handler: function () {
                    $('#e_grid_dtl').edatagrid('reload');
                }
            },
            {
                iconCls: 'icon-add', text: '新增', handler: function () {
                    $('#e_grid_dtl').edatagrid('addRow');
                }
            },
            {
                iconCls: 'icon-edit', text: '修改', handler: function () {
                    let selected = $('#e_grid_dtl').edatagrid('getSelected');
                    if (selected != undefined && selected.id) {
                        let selectIndex = $('#e_grid_dtl').edatagrid('getRowIndex', selected);
                        $('#e_grid_dtl').edatagrid('editRow', selectIndex);
                    }
                }
            },
            {
                iconCls: 'icon-save', text: '保存', handler: function () {
                    $('#e_grid_dtl').edatagrid('saveRow');
                }
            },
            {
                iconCls: 'icon-application_delete', text: '取消更改', handler: function () {
                    $('#e_grid_dtl').edatagrid('cancelRow');
                }
            },
            {
                iconCls: 'icon-cancel', text: '删除', handler: function () {
                    let selected = $('#e_grid_dtl').edatagrid('getSelected');
                    if (selected != undefined && selected.id) {
                        $('#e_grid_dtl').edatagrid('destroyRow');
                    }
                }
            },
        ]
    })
}

function btn_search() {
    $('#e_grid').edatagrid('reload');
}

function btn_add() {
    $('#e_grid').edatagrid('addRow');
}

function btn_modify() {
    let selected = $('#e_grid').edatagrid('getSelected');
    if (selected != undefined) {
        let index = $('#e_grid').edatagrid('getRowIndex', selected);
        if (index != -1) {
            $('#e_grid').edatagrid('editRow', index);
        }
    }
}

function btn_delete() {
    let selected = $('#e_grid').edatagrid('getSelected');
    if (selected != undefined) {
        let index = $('#e_grid').edatagrid('getRowIndex', selected);
        if (index != -1) {
            $('#e_grid').edatagrid('destroyRow', index);
        }
    }
}

function btn_import() {

}

function btn_save() {
    $('#e_grid').edatagrid('saveRow');
}

function btn_export() {
    $('#e_grid').datagrid('toExcel', {
        filename: '用户列表.xls',
        worksheet: 'Worksheet',
        caption: 'Caption',
        rows: $('#e_grid').edatagrid('getFormatRows'),
    });
}